/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.upf.grupof.projectphotos.messagesys;

import edu.upf.grupof.projectphotos.databases.*;
import edu.upf.grupof.projectphotos.messageobj.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

/**
 *
 * @author fredi
 */
public class Listener implements PacketListener {

    private String packetid1 = "message";
    private InstantMessage instantMessage = null;
    private final static Log log = LogFactory.getLog(Listener.class);


    //Constructor
    public Listener(InstantMessage instantmessage) {
        this.instantMessage = instantmessage;
    }

    //Method that processes the packets when they are received
    public void processPacket(Packet packet){

        //Look if the packet is Message types
        //It would not be necessary as the listener's filter just allow Message type to be sent
        if (packet instanceof Message) {

            Message msg = (Message) packet;
            if (msg.getPacketID().equalsIgnoreCase(packetid1)) {

                //If it is a search
                if (msg.getProperty(packetid1) instanceof SearchProfile) {

                    SearchProfile sp = (SearchProfile) msg.getProperty(packetid1);
                    //Getting the constants from it
                    String ori = sp.getOrigen();
                    String dst = sp.getDest();
                    List<String> lst = sp.getTags();
                    String type= sp.getType();

                    
                    int x=0;
                    String[] parameters = new String[lst.size()];
                    for (Iterator<String> i = lst.iterator(); i.hasNext();) {
                        parameters[x]=i.next();
                        x++;
                    }
      
                    //Creating the SearchResult
                    SearchResult sr = new SearchResult(dst, ori);

                    /**
                     * Parte a implementar con la base de datos
                     */
                    DBManager manager=DBManager.getInstance();
                    
                    DBAction action = new DBAction();
                    action.setActionId(type);
                    action.setParameters(parameters);
                    
                    DBActionResult result=(DBActionResult) manager.execute(action);
                    
                    /**
                     * Fin de parte de acceso a la base de datos.
                     */
                    if(result.isOk()){
                        List<iPhoto> photos=result.getResult();
                        Iterator it = photos.iterator();
                        while(it.hasNext()){
                            Photo p=(Photo) it.next();
                            //Thumbnail icon=new Thumbnail(p.getPath());
                            Contents ct=new Contents(p);
                            sr.addContents(ct);
                        }
                    }
                    try {
                        instantMessage.sender(sr);
                    } catch (XMPPException ex) {
                        Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else if (msg.getProperty(packetid1) instanceof SearchResult) {

                    //Obtaining the SearchResult from the GenericMessage
                    SearchResult sr = (SearchResult) msg.getProperty(packetid1);
                    
                    if (sr.getContents().size() > 0) {
                        
                        //Passar contents a interficie per imprimir
                        List<Contents> c=sr.getContents();
                        List<iPhoto> photos = new ArrayList<iPhoto>();
                        Iterator it=c.iterator();
                        while(it.hasNext()){
                            Contents cnt = (Contents) it.next();
                            Photo p=cnt.getPhotos();
                            photos.add(p);
                            System.out.println("Resultats");
                            System.out.println(p.getTitle());
                            System.out.println(p.getDesc());
                            System.out.println(p.getPath());
                            System.out.println(p.getUser());
                            System.out.println(p.getSize());
                            
                        }
                        instantMessage.getResults(photos);
                    } else {
                        log.info("There are no results.");
                    }
                } else if (msg.getProperty(packetid1) instanceof UserContent){
                    
                    UserContent uc = (UserContent) msg.getProperty(packetid1);
                    
                    log.info("Descargando foto " + uc.getName());
                    
                    ThreadS sender= new ThreadS(uc,msg,instantMessage);
                    sender.start();
                }
            }
        }
    }
}
